package com.zm.core;

import ch.ethz.ssh2.Connection;
import com.zm.util.Ssh2Pool;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;


/**
 * Created by ZM on 2022/2/17 16:13
 */

public class TestMain {
    public static void main(String[] args) throws InterruptedException {
        Ssh2Pool pool=Ssh2Pool.getInstance();
        pool.initPool();
        TestMain testMain = new TestMain();
        testMain.test1(pool);

    }

    private void test2(Ssh2Pool pool) {
            pool.initPool();
            pool.closePool();
    }

    private void test1(Ssh2Pool pool) throws InterruptedException {
        //String tempPath = null;
        try {
            for (int i = 1; i <=50; i++) {//使用50个线程去获取连接
                new Thread(()-> {
                        try {
                            System.out.println("线程"+Thread.currentThread().getName()+"，开始获取连接...");
                            Connection conn=pool.getConnection();
                            Random random = new Random();
                            int t = random.nextInt(6);
                            //每个线程随机睡眠0~5秒
                            TimeUnit.SECONDS.sleep(t);
                            if (conn!=null){
                                pool.releaseConnection(conn);
                            }
                            TimeUnit.MILLISECONDS.sleep(t*100);//每个线程睡眠0到500毫秒后执行一次缩小连接池的操作
                            pool.narrowPools();//手动执行一次连接池的缩小操作
                        } catch (InterruptedException exception) {
                            exception.printStackTrace();
                        }
                },String.valueOf(i)).start();
                //获取连接connection后就可以进行操作了。。。
            }


        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            TimeUnit.SECONDS.sleep(30);
            pool.closePool();
        }

    }

}
